<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>新增SPU</el-breadcrumb-item>
      <el-breadcrumb-item>{{$router.currentRoute.name}}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
      <el-form-item label="品牌" prop="brandId">
        <el-select v-model="ruleForm.brandId" placeholder="请选择品牌" style="width: 300px;">
          <el-option
              v-for="item in brandListOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="属性模板" prop="attributeTemplateId">
        <el-select v-model="ruleForm.attributeTemplateId" placeholder="请选择属性模板" style="width: 300px;">
          <el-option
              v-for="item in attributeTemplateIdListOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="商品名称" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title"></el-input>
      </el-form-item>
      <el-form-item label="简介" prop="description">
        <el-input v-model="ruleForm.description"></el-input>
      </el-form-item>
      <el-form-item label="货号" prop="typeNumber">
        <el-input v-model="ruleForm.typeNumber"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="计件单位" prop="unit">
            <el-input v-model="ruleForm.unit"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="售价" prop="listPrice">
            <el-input v-model="ruleForm.listPrice">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="库存" prop="stock">
            <el-input v-model="ruleForm.stock">
              <template v-if="ruleForm.unit" slot="append">{{ ruleForm.unit }}</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="库存阈警值" prop="stockThreshold">
            <el-input v-model="ruleForm.stockThreshold">
              <template v-if="ruleForm.unit" slot="append">{{ ruleForm.unit }}</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="关键词" prop="keywords">
        <el-input v-model="ruleForm.keywords"></el-input>
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-input v-model="ruleForm.tags"></el-input>
      </el-form-item>
      <el-form-item label="排序序号" prop="sort">
        <el-input v-model="ruleForm.sort"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" @click="backToPreStep()">上一步</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">下一步</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  data() {
    return {
      brandListOptions: [],
      attributeTemplateIdListOptions: [],
      ruleForm: {},
      //表单规则
      rules: {
        brandId: [
          {type: 'number', required: true, message: '请选择品牌', trigger: 'blur'},
        ],
        attributeTemplateId: [
          {type: 'number', required: true, message: '请选择属性模板', trigger: 'blur'},
        ],
        name: [
          {required: true, message: '请输入商品名称', trigger: 'blur'},
        ],
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'},
        ],
        description: [
          {required: true, message: '请输入简介', trigger: 'blur'},
        ],
        unit: [
          {required: true, message: '请输入计件单位', trigger: 'blur'},
        ],
        listPrice: [
          {required: true, message: '请输入售价', trigger: 'blur'},
        ],
        typeNumber: [
          {required: true, message: '请输入货号', trigger: 'blur'},
        ],
        stock: [
          {required: true, message: '请输入库存', trigger: 'blur'},
        ],
        stockThreshold: [
          {required: true, message: '请输入库存阈警值', trigger: 'blur'},
        ],
        keywords: [
          {required: true, message: '请输入关键词', trigger: 'blur'},
        ],
        tags: [
          {required: true, message: '请输入标签', trigger: 'blur'},
        ],
        sort: [
          {required: true, message: '请输入排序序号', trigger: 'blur'},
        ]
      }
    }
  },
  methods: {
    // 加载品牌列表
    loadBrandList() {
      let url = "http://localhost:9480/brands?queryType=all";

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.brandListOptions = jsonResult.data.list;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    // 加载属性模板列表
    loadAttributeTemplateList() {
      let url = "http://localhost:9480/attribute-templates?queryType=all";

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.attributeTemplateIdListOptions = jsonResult.data.list;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    // 加载本地存储的表单数据
    loadLocalRuleForm() {
      let localRuleFormString = localStorage.getItem('localRuleForm');
      let localRuleForm = JSON.parse(localRuleFormString);
      //第一步数据不存在
      if(!localRuleForm || !localRuleForm.categoryId){
        this.$router.push("add-new-1");
        return;
      }

      this.ruleForm = localRuleForm;
    },
    submitForm(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //开始验证品牌
          this.validBrandId();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //返回上一步
    backToPreStep(){
      this.$router.push("add-new-1");
    },
    validBrandId(){
      let url = "http://localhost:9480/brands/" + this.ruleForm.brandId;
      console.log('url = ' + url);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          //开始验证属性模板
          this.ruleForm.brandName = jsonResult.data.name;
          this.validAttributeTemplateId();
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    validAttributeTemplateId(){
      let url = "http://localhost:9480/attribute-templates/" + this.ruleForm.attributeTemplateId;
      console.log('url = ' + url);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
           let ruleForm = JSON.stringify(this.ruleForm);
          localStorage.setItem("localRuleForm", ruleForm);
          this.$router.push('add-new-3');
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAttributeTemplateList();
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.loadBrandList();
    this.loadAttributeTemplateList();
    this.loadLocalRuleForm();
  }
}
</script>